import Taro, { Component } from '@tarojs/taro'
import { View, Text, ScrollView } from '@tarojs/components'

import './index.scss'

import good from '../../../service/good'

import GoodItem from '../../../components/orderFood/goodItem'
import NoData from '../../../components/noData'
import GoodSpec from '../goodSpec'

class Index extends Component {
	static options = {
		addGlobalClass: true
	}
	static defaultProps = {
		onGoodListScope() {}
	}
	constructor() {
		super(...arguments)
		this.state = {
			goodList: [],
			pageindex: 1,
			hasEd: false,
			hasView: false,
			cid: null,  // 分类id
			specState: false, // 商品弹窗显示状态
			goodSpec: null, // 弹窗商品
		};
	}
	// 获取商品详情弹窗作用域
	getGoodSpecScope(obj){
		this.goodSpecScope = obj
	}
	componentWillMount(obj){
		this.props.onGoodListScope(this)
		this.getGoodSpecScope(obj)
		// let { orderType } = this.props
		// if(orderType == '0'){ // 无桌
		// 	this.getGoodscate()
		// }
		// this.getGoodList()
	}
	// 无桌点餐
	getGoodList(cid,e){
		if(e){ // 切换导航
			this.setState({
				pageindex: 1,
				hasView: false,
				hasEd: false
			})
		}else{
			this.state.pageindex++
		}
		let goodLists = []
		good.getGoodList({cid: cid,pageindex: this.state.pageindex},(goodList,hasEd) => {
			goodLists = this.state.pageindex == 1 ? goodList : this.state.goodList.concat(goodList)
			this.setState({
				goodList: goodLists,
				hasEd,
				cid,
				hasView: true,
			})
		},() => {
			this.setState({
                goodList: [],
				hasView: true,
            })
		})
	}
	// 上拉加载更多
	scrollToLower(){
		let {cid,hasEd} = this.state
		if(hasEd){ return }
		this.getGoodList(cid)
	}
	// 商品购买弹窗切换
	changeGoodSpec(data){
		if(data.type && data.type == "tap"){ 
			this.setState({specState: !this.state.specState})
		}else{
			this.goodSpecScope.getGoodDetail({gid: data.ID},() => {
				this.setState({specState: !this.state.specState})
			})
		}
	}

	render() {
		let {hasView,goodList,hasEd,cid,specState,goodSpec} = this.state
		return (
			<Block>
				<ScrollView className='comGoodList' scrollY onScrollToLower={this.scrollToLower.bind(this,cid)}>
					{hasView ? 
						<View>
							{goodList.length > 0 ? 
								<Block>
									{goodList.map((item,i) => (
										<GoodItem key={'goodItem' + i} goodItem={item} onChangeGoodSpec={this.changeGoodSpec.bind(this,item)}></GoodItem>
									))}
									{hasEd && <NoData type='2'></NoData>}
								</Block>
								: 
								<NoData type='1'></NoData>
							}
						</View>
						: 
						<NoData type='3'></NoData>
					}
				</ScrollView>
				{/* 商品加入购物车弹窗 */}
				<GoodSpec specState={specState} goodSpec={goodSpec} onGoodSpecScope={this.getGoodSpecScope.bind(this)} onChangeGoodSpec={this.changeGoodSpec.bind(this)}></GoodSpec>
			</Block>
		)
	}
}
export default Index;